﻿using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using UnityEngine;
using WssEvents;

namespace JQMergeFramework
{
    public class CopterUnit : MonoBehaviour
    {
        
        public Transform guidedMissileNode;

        public Transform models;
        
        public Transform airfoil1;
        public Transform airfoil2;

        //是否点击
        private bool isClickDown = false;
        
        private void OnDisable()
        {
            GlobalEvent.Removelistener<EventTypes>(GameEvents.OnTargetEvent,OnTargetEvent);
            GlobalEvent.Removelistener<EventTypes>(GameEvents.OnShowEvent,ShowEvent);
            GlobalEvent.Removelistener<EventTypes>(GameEvents.OnCancelUseEvent,DOPlay);
        }

        private void OnEnable()
        {
            GlobalEvent.Addlistener<EventTypes>(GameEvents.OnTargetEvent,OnTargetEvent);
            GlobalEvent.Addlistener<EventTypes>(GameEvents.OnShowEvent,ShowEvent);
            GlobalEvent.Addlistener<EventTypes>(GameEvents.OnCancelUseEvent,DOPlay);
        }

        private void DOPlay(EventTypes types)
        {
            if (types == EventTypes.Helicopter)
            {
                this.DOPlay();
                this.transform.DOPlay();
                DOTween.Play(this.GetInstanceID());
            }
        }
        
        
        public void ShowEvent(EventTypes types)
        {
            if (types != EventTypes.Helicopter)
            {
                return;
            }
            
            float speed = 10;
            float y = MainCityControl.I.GetCityNodeHeight(true) + 20;
            
            Vector3 startPos = new Vector3(-50,y,0);
            Vector3 endPos = new Vector3(50,y,0);

            this.transform.position = startPos;
            this.models.gameObject.SetActive(true);
            
            Vector3[] path = new Vector3[3];
            path[0] = startPos;
            path[2] = endPos;
            path[1] = (path[0] + path[2]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-20, -10));
            float pathLen = CommonFun.CalculateTotalLength(path);
            float runTime = pathLen / speed;
        
            
            Vector3[] path2 = new Vector3[3];
            path2[0] = endPos;
            path2[2] = startPos;
            path2[1] = (path2[0] + path2[2]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(0, 20));
            float pathLen2 = CommonFun.CalculateTotalLength(path2);
            float runTime2 = pathLen2 / speed;
            
            Sequence sq = DOTween.Sequence();
            sq.SetId(this.GetInstanceID());
            sq.Append(this.transform.DOPath(path, runTime, PathType.Linear).SetEase(Ease.Linear).OnWaypointChange((idx) =>
            {
                if (idx+1 <path.Length)
                {
                    this.transform.DOLookAt(path[idx + 1], 0.2F);
                }
            }));
            sq.Append(this.transform.DOPath(path2, runTime, PathType.CatmullRom).SetEase(Ease.Linear).OnWaypointChange((idx)=>{
                if (idx+1 < path2.Length)
                {
                    this.transform.DOLookAt(path2[idx + 1], 0.2F);
                }
            }));
            sq.OnComplete(() =>
            {
                this.models.gameObject.SetActive(false);
            });
            
  
            //旋转直升机
            airfoil1.DOLocalRotate(new Vector3(0, 360, 0), 0.5f, RotateMode.WorldAxisAdd).SetEase(Ease.Linear)
                .SetLoops(-1, LoopType.Incremental);
            airfoil2.DOLocalRotate(new Vector3(360,0,0), 0.5f, RotateMode.LocalAxisAdd).SetEase(Ease.Linear)
                .SetLoops(-1, LoopType.Incremental);
        }

        private void OnMouseDown()
        {
            isClickDown = true;
        }

        private void OnMouseUp()
        {
            if (isClickDown && !MergeManager.Instance.isGameOver)
            {
                this.DOPause();
                this.transform.DOPause();
                DOTween.Pause(this.GetInstanceID());
                //UI弹窗
                UIManager.Instance.GetWindow<UIEvent>().Open(EventTypes.Helicopter);
            }
            isClickDown = false;
        }

        public void OnTargetEvent(EventTypes types)
        {
            if (types != EventTypes.Helicopter)
            {
                return;
            }

            
            InputManager.I.isNoRayClick = true;
            
            this.models.gameObject.SetActive(true);
            
            InputManager.I.isNoRayClick = true;

            TowerControl towerControl = TowerControl.I;
            CityBaseControl cityBaseControl = CityBaseControl.I;
            
            Vector3 endTrackPos = towerControl.trackPoint[0].position;

            
            float y = MainCityControl.I.GetCityNodeHeight() + 20;
            
            Vector3 stopPos = new Vector3(0,y,0) + new Vector3(cityBaseControl.chessboardSize.x/4,0,cityBaseControl.chessboardSize.z/4);


            Vector3 fo = new Vector3(0.5F, 0, 0.5F);
            Vector3 startPos = stopPos + (fo.normalized * 50);

            //飞行
            Sequence sq = DOTween.Sequence();
            
            sq.Append(this.transform.DOLookAt(stopPos, 0.5f));
            sq.Append(this.transform.DOMove(stopPos, 1.5f));

            List<CityUnit> cityList = MergeManager.Instance.GetLowCity();
            for (int i = 0; i < cityList.Count; i++)
            {
                GameObject guidedMissileObj =  EffectPool.I.GetPoolObject(PoolName.GuidedMissile);
                guidedMissileObj.transform.SetParent(this.guidedMissileNode);
                guidedMissileObj.transform.localPosition = Vector3.zero;
                guidedMissileObj.transform.localEulerAngles = Vector3.zero;
            
                
                Vector3 cityPos = cityList[i].transform.position;
                int tempIndex = i;
                //转身
                sq.Append(this.transform.DOLookAt(new Vector3(cityPos.x,this.transform.position.y,cityPos.z), 0.5F).SetEase(Ease.Linear));
                
                //导弹下降
                sq.Append(guidedMissileObj.transform.DOMoveY(guidedMissileObj.transform.position.y - 10, 0.3F)
                    .SetEase(Ease.InOutExpo));
                sq.AppendInterval(0.1f);
                
                sq.AppendCallback(() =>
                {
                    guidedMissileObj.GetComponentInChildren<ParticleSystem>()?.Play();
                    // guidedMissileObj.transform.Rotate(q.eulerAngles, 0.1F);
                });
                sq.Append(guidedMissileObj.transform.DOMove(cityPos, 0.5F)
                    .SetEase(Ease.InOutExpo));
         
                sq.AppendCallback(() =>
                {
                    guidedMissileObj.transform.DOKill();
                    guidedMissileObj.GetComponentInChildren<ParticleSystem>()?.Stop();
                    EffectPool.I.PutPoolObject(PoolName.GuidedMissile,guidedMissileObj);
                    
                   GameObject cityBomb =  EffectPool.I.GetPoolObject(PoolName.CityBomb);
                   cityBomb.transform.position = cityPos;
                   
                   //删除房子
                   cityList[tempIndex].RDestroy();
                   
                   EffectPool.I.PutPoolObject(PoolName.CityBomb,cityBomb,1);
                });
            }

            sq.AppendCallback(() =>
            {
                InputManager.I.isNoRayClick = false;
            });
            
            sq.Append(this.transform.DOLocalRotate(new Vector3(0, 45, 0), 0.4F));
            sq.Append(this.transform.DOMove(startPos, 0.5F));
            
            sq.AppendCallback(() =>
            {
                this.models.gameObject.SetActive(false);
                airfoil1.DOKill();
                airfoil2.DOKill();
            });

            sq.Play();
        }
        
    }
}